<%--
  Created by IntelliJ IDEA.
  User: jiang
  Date: 2021/7/22
  Time: 10:00
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>用户管理</title>
    <link rel="stylesheet" href="${pageContext.request.contextPath}/resources/component/pear/css/pear.css"/>
</head>
<body class="pear-container">
<div class="layui-card">
    <div class="layui-card-body">
        <form class="layui-form" action="">
            <div class="layui-form-item">
                <div class="layui-form-item layui-inline">
                    <label class="layui-form-label">用户名</label>
                    <div class="layui-input-inline">
                        <input type="text" name="realname" placeholder="" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item layui-inline">
                    <label class="layui-form-label">性别</label>
                    <div class="layui-input-inline">
                        <select name="sex">
                            <option value="">请选择</option>
                            <option value="1">男</option>
                            <option value="0">女</option>
                        </select>
                    </div>
                </div>

                <div class="layui-form-item layui-inline">
                    <label class="layui-form-label">证件号码</label>
                    <div class="layui-input-inline">
                        <input type="text" name="idCard" placeholder="" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item layui-inline">
                    <label class="layui-form-label">电话号码</label>
                    <div class="layui-input-inline">
                        <input type="text" name="phone" placeholder="" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item layui-inline">
                    <button class="pear-btn pear-btn-md pear-btn-primary" lay-submit lay-filter="user-query">
                        <i class="layui-icon layui-icon-search"></i>
                        查询
                    </button>
                    <button type="reset" class="pear-btn pear-btn-md">
                        <i class="layui-icon layui-icon-refresh"></i>
                        重置
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>
<div class="layui-card">
    <div class="layui-card-body">
        <table id="user-table" lay-filter="user-table"></table>
    </div>
</div>
</body>
<script type="text/html" id="user-toolbar">
    <shiro:hasPermission name="user:add">
        <button class="pear-btn pear-btn-primary pear-btn-md" lay-event="add">
            <i class="layui-icon layui-icon-add-1"></i>
            新增
        </button>
    </shiro:hasPermission>
    <shiro:hasPermission name="user:delete">
        <button class="pear-btn pear-btn-danger pear-btn-md" lay-event="batchRemove">
            <i class="layui-icon layui-icon-delete"></i>
            删除
        </button>
    </shiro:hasPermission>
</script>

<script type="text/html" id="user-bar">
    <shiro:hasPermission name="user:update">
        <button class="pear-btn pear-btn-primary pear-btn-sm" lay-event="edit"><i
                class="layui-icon layui-icon-edit"></i>
        </button>
    </shiro:hasPermission>
    <shiro:hasPermission name="user:delete">
        <button class="pear-btn pear-btn-danger pear-btn-sm" lay-event="remove"><i
                class="layui-icon layui-icon-delete"></i>
        </button>
    </shiro:hasPermission>
    <shiro:hasRole name="admin">
        <button class="pear-btn pear-btn-success pear-btn-sm" lay-event="assign"><i
                class="layui-icon layui-icon-auz"></i>
        </button>
    </shiro:hasRole>
</script>

<script type="text/html" id="user-enable">
    <input type="checkbox" name="enable" value="{{d.id}}" lay-skin="switch" lay-text="启用|禁用" lay-filter="user-enable" {{
           d.deleted== 1 ? 'checked': ''}}>
</script>

<script type="text/html" id="user-sex">
    {{# if (d.sex == 1) { }}
    <span>男</span>
    {{# }else if(d.sex == 0){ }}
    <span>女</span>
    {{# } }}
</script>

<script type="text/html" id="user-img">
   <img onclick="change(this)" src="${pageContext.request.contextPath}/{{d.img}}" width="45px" height="45px" onerror="javascript:this.src ='${pageContext.request.contextPath}/resources/admin/images/avatar.jpg'"/>
</script>

<script type="text/html" id="user-createTime">
    {{layui.util.toDateString(d.createTime, 'yyyy-MM-dd HH:mm:ss')}}
</script>

<script type="text/html" id="user-form-add" lay-filter="user-form-add">
    <div class="layui-card">
        <div class="layui-card-body">
            <form class="layui-form" action="">
                <div class="layui-form-item">
                    <label class="layui-form-label">登录名</label>
                    <div class="layui-input-block">
                        <input type="text" name="loginName" placeholder="请输入登录名" class="layui-input"
                               lay-verify="required"/>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">密码</label>
                    <div class="layui-input-block">
                        <input type="password" name="loginPassword" lay-verify="required" autocomplete="off"
                               placeholder="请输入密码" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-form-item layui-inline">
                        <label class="layui-form-label">真实姓名</label>
                        <div class="layui-input-inline">
                            <input type="text" name="realname" placeholder="请输入真实姓名" lay-verify="required"
                                   class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item layui-inline">
                        <label class="layui-form-label">性别</label>
                        <div class="layui-input-inline">
                            <input type="radio" name="sex" value="0" title="男"/>
                            <input type="radio" name="sex" value="1" title="女" checked/>
                        </div>
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">证件号码</label>
                    <div class="layui-input-block">
                        <input type="text" name="idCard" placeholder="" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">电话号码</label>
                    <div class="layui-input-block">
                        <input type="text" name="phone" placeholder="请输入电话号码" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">地址</label>
                    <div class="layui-input-block">
                        <input type="text" name="address" placeholder="请输入家庭住址" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">头像</label>
                    <div class="layui-input-block">
                        <input type="hidden" name="img" id="userImg"/>
                        <div class="layui-upload">
                            <button type="button" class="layui-btn" id="uploadImg">上传图片</button>
                            <div class="layui-upload-list">
                                <img class="layui-upload-img" id="imgArea" width="92px" height="92px" border="none">
                                <p id="uploadText"></p>
                            </div>
                            <div style="width: 95px;">
                                <div class="layui-progress layui-progress-big" lay-showpercent="yes" lay-filter="demo">
                                    <div class="layui-progress-bar" lay-percent=""></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="layui-form-item" style="text-align: center">
                    <div class="layui-inline">
                        <button class="pear-btn pear-btn-md pear-btn-primary" lay-submit lay-filter="user-add">
                            <i class="layui-icon">&#xe605;</i>
                            确认
                        </button>
                        <button type="reset" class="pear-btn pear-btn-md">
                            <i class="layui-icon layui-icon-refresh"></i>
                            取消
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</script>

<script type="text/html" id="user-form-update">
    <div class="layui-card">
        <div class="layui-card-body">
            <form class="layui-form" lay-filter="updateUserFrm" action="">
                <div class="layui-form-item">
                    <label class="layui-form-label">登录名</label>
                    <div class="layui-input-block">
                        <input type="hidden" name="id" value="">
                        <input type="text" name="loginName" placeholder="请输入登录名" class="layui-input"
                               lay-verify="required" readonly/>
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">旧的密码</label>
                    <div class="layui-input-block">
                        <input type="password" name="oldPassword" lay-verify="required" autocomplete="off"
                               placeholder="请输入密码" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">新的密码</label>
                    <div class="layui-input-block">
                        <input type="password" name="newPassword" lay-verify="required" autocomplete="off"
                               placeholder="请输入密码" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-form-item layui-inline">
                        <label class="layui-form-label">真实姓名</label>
                        <div class="layui-input-inline">
                            <input type="text" name="realname" placeholder="请输入真实姓名" lay-verify="required"
                                   class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item layui-inline">
                        <label class="layui-form-label">性别</label>
                        <div class="layui-input-inline">
                            <input type="radio" name="sex" value="1" title="男"/>
                            <input type="radio" name="sex" value="0" title="女" checked/>
                        </div>
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">证件号码</label>
                    <div class="layui-input-block">
                        <input type="text" name="idCard" placeholder="" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">电话号码</label>
                    <div class="layui-input-block">
                        <input type="text" name="phone" placeholder="请输入电话号码" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">地址</label>
                    <div class="layui-input-block">
                        <input type="text" name="address" placeholder="请输入家庭住址" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">头像</label>
                    <div class="layui-input-block">
                        <input type="hidden" name="img" id="updateImg"/>
                        <div class="layui-upload">
                            <button type="button" class="layui-btn" id="uploadUpdateImg">上传图片</button>
                            <div class="layui-upload-list">
                                <img class="layui-upload-img" id="imgUpdateArea" width="92px" height="92px" border="none">
                                <p id="uploadUpdateText"></p>
                            </div>
                            <div style="width: 95px;">
                                <div class="layui-progress layui-progress-big" lay-showpercent="yes" lay-filter="demo">
                                    <div class="layui-progress-bar" lay-percent=""></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">状态</label>
                    <div class="layui-input-block">
                        <input type="radio" name="deleted" value="1" title="启动" checked>
                        <input type="radio" name="deleted" value="0" title="禁用">
                    </div>
                </div>
                <div class="layui-form-item" style="text-align: center">
                    <div class="layui-inline">
                        <button class="pear-btn pear-btn-md pear-btn-primary" lay-submit lay-filter="user-update">
                            <i class="layui-icon">&#xe605;</i>
                            确认
                        </button>
                        <button type="reset" class="pear-btn pear-btn-md">
                            <i class="layui-icon layui-icon-refresh"></i>
                            取消
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</script>

<script type="text/html" id="user-form-assign">
    <div class="layui-card">
        <div class="layui-card-body">
            <form class="layui-form" lay-filter="assignUserFrm" action="">
                <div class="layui-form-item">
                    <label class="layui-form-label">选择角色</label>
                    <div class="layui-input-block">
                        <input type="hidden" name="id">
                        <ul id="roleTree" class="dtree" data-id="0"></ul>
                    </div>
                </div>

                <div class="layui-form-item" style="text-align: right">
                    <div class="layui-inline">
                        <button class="pear-btn pear-btn-md pear-btn-primary" lay-submit lay-filter="user-assign">
                            <i class="layui-icon">&#xe605;</i>
                            确认
                        </button>
                        <button type="reset" class="pear-btn pear-btn-md" lay-filter="close" lay-submit="">
                            <i class="layui-icon layui-icon-close"></i>
                            关闭
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</script>

<script src="${pageContext.request.contextPath}/resources/component/layui/layui.js"></script>
<script src="${pageContext.request.contextPath}/resources/component/pear/pear.js"></script>
<script>

    layui.use(['table', 'form', 'jquery', 'common', 'dtree','upload', 'element'], function () {
        let table = layui.table;
        let form = layui.form;
        let $ = layui.jquery;
        let common = layui.common;
        let dtree = layui.dtree;
        let upload = layui.upload;
        let element = layui.element;

        let MODULE_PATH = "operate/";

        let cols = [
            [{
                type: 'checkbox'
            },
                {
                    title: '账号',
                    field: 'loginName',
                    align: 'center',
                    width: 120
                },
                {
                    title: '真实姓名',
                    field: 'realname',
                    align: 'center'
                },
                {
                    title: '性别',
                    field: 'sex',
                    align: 'center',
                    width: 80,
                    templet: '#user-sex'
                },
                {
                    title: '电话',
                    field: 'phone',
                    align: 'center'
                },
                {
                    title: '证件号码',
                    field: 'idCard',
                    align: 'center'
                },
                {
                    title: '用户住址',
                    field: 'address',
                    align: 'center'
                },
                {
                    title: '用户头像',
                    field: 'img',
                    align: 'center',
                    templet: '#user-img'
                },
                {
                    title: '注册时间',
                    field: 'createTime',
                    align: 'center',
                    templet: '#user-createTime'
                },
                {
                    title: '是否启用',
                    field: 'deleted',
                    align: 'center',
                    templet: '#user-enable'
                },
                {
                    title: '操作',
                    toolbar: '#user-bar',
                    align: 'center',
                    width: 150
                }
            ]
        ]

        window.change = function(obj){
            layer.open({
                type:1,
                title:'头像查看',
                skin:'none', // 加上边框
                area:['400px', '420px'],
                content: '<div><img src="'+ obj.src +'" width="400px" height="350px"></div>'
            })
        }

        table.render({
            elem: '#user-table',
            url: '${pageContext.request.contextPath}/user/findByPage.do',
            page: true,
            cols: cols,
            skin: 'line',
            toolbar: '#user-toolbar',
            defaultToolbar: [{
                title: '刷新',
                layEvent: 'refresh',
                icon: 'layui-icon-refresh',
            }, 'filter', 'print', 'exports']
            , parseData: function (res) {
                //res 即为原始返回的数据
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.data.total, //解析数据长度
                    "data": res.data.list //解析数据列表
                };
            }
            , response: {

                statusName: 'code' //规定数据状态的字段名称，默认：code
                , statusCode: 200 //规定成功的状态码，默认：0
                , msgName: 'msg' //规定状态信息的字段名称，默认：msg
                , dataName: 'data' //规定数据列表的字段名称，默认：data
            }
        });

        table.on('tool(user-table)', function (obj) {
            if (obj.event === 'remove') {
                console.log(obj)
                window.remove(obj);
            } else if (obj.event === 'edit') {
                window.edit(obj);
            } else if (obj.event === 'assign') {
                window.assign(obj);
            }
        });

        table.on('toolbar(user-table)', function (obj) {
            if (obj.event === 'add') {
                window.add();
            } else if (obj.event === 'refresh') {
                window.refresh();
            } else if (obj.event === 'batchRemove') {
                window.batchRemove(obj);
            }
        });

        form.on('submit(user-query)', function (data) {
            table.reload('user-table', {
                where: data.field
            })
            return false;
        });

        form.on('switch(user-enable)', function (obj) {
            $.post("${pageContext.request.contextPath}/user/enable.do?id=" + obj.value, function (res) {
                if (res.code == 200) {
                    table.reload('user-table');
                }
                layer.msg(res.msg)
            });
        });


        let mainIndex;

        window.add = function () {
            mainIndex = layer.open({
                type: 1,
                title: '新增用户',
                shade: 0.1,
                area: ['800px', '700px'],
                content: $("#user-form-add").html(),
                success: function (layero, index) {
                    // 渲染表单的元素
                    form.render('radio');
                    //常规使用 - 普通图片上传
                    var uploadInst = upload.render({
                        elem: '#uploadImg'
                        ,url: '${pageContext.request.contextPath}/file/uploadImg.do' //改成您自己的上传接口
                        ,acceptMime:'image/*'
                        ,field:'file'
                        ,before: function(obj){
                            //预读本地文件示例，不支持ie8
                            obj.preview(function(index, file, result){
                                $('#imgArea').attr('src', result); //图片链接（base64）
                            });

                            element.progress('demo', '0%'); //进度条复位
                            layer.msg('上传中', {icon: 16, time: 0});
                        }
                        ,done: function(res){
                            //如果上传失败
                            if(res.code != 200){
                                return layer.msg('上传失败');
                            }
                            //上传成功的一些操作

                            $('#userImg').val(res.data);
                            $('#uploadText').html(''); //置空上传失败的状态
                        }
                        ,error: function(){
                            //演示失败状态，并实现重传
                            var uploadText = $('#uploadText');
                            uploadText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                            uploadText.find('.demo-reload').on('click', function(){
                                uploadInst.upload();
                            });
                        }
                        //进度条
                        ,progress: function(n, elem, e){
                            element.progress('demo', n + '%'); //可配合 layui 进度条元素使用
                            if(n == 100){
                                layer.msg('上传完毕', {icon: 1});
                            }
                        }
                    });
                }
            });
        }

        window.edit = function (obj) {
            mainIndex = layer.open({
                type: 1,
                title: '修改用户',
                shade: 0.1,
                area: ['1000px', '600px'],
                content: $("#user-form-update").html(),
                success: function (layero, index) {
                    form.render('radio');
                    form.val("updateUserFrm", obj.data);
                    console.log(obj.data);
                    $('#imgUpdateArea').attr('src', '${pageContext.request.contextPath}/' + obj.data.img);
                    //常规使用 - 普通图片上传
                    var uploadInst = upload.render({
                        elem: '#uploadUpdateImg'
                        ,url: '${pageContext.request.contextPath}/file/uploadImg.do' //改成您自己的上传接口
                        ,acceptMime:'image/*'
                        ,field:'file'
                        ,before: function(obj){
                            //预读本地文件示例，不支持ie8
                            obj.preview(function(index, file, result){
                                $('#imgUpdateArea').attr('src', result); //图片链接（base64）
                            });

                            element.progress('demo', '0%'); //进度条复位
                            layer.msg('上传中', {icon: 16, time: 0});
                        }
                        ,done: function(res){
                            //如果上传失败
                            if(res.code != 200){
                                return layer.msg('上传失败');
                            }
                            //上传成功的一些操作

                            $('#updateImg').val(res.data);
                            $('#uploadUpdateText').html(''); //置空上传失败的状态
                        }
                        ,error: function(){
                            //演示失败状态，并实现重传
                            var uploadText = $('#uploadUpdateText');
                            uploadText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                            uploadText.find('.demo-reload').on('click', function(){
                                uploadInst.upload();
                            });
                        }
                        //进度条
                        ,progress: function(n, elem, e){
                            element.progress('demo', n + '%'); //可配合 layui 进度条元素使用
                            if(n == 100){
                                layer.msg('上传完毕', {icon: 1});
                            }
                        }
                    });
                }
            });
        }

        window.remove = function (obj) {
            layer.confirm('确定要删除该用户', {
                icon: 3,
                title: '提示'
            }, function (index) {
                layer.close(index);
                let loading = layer.load();
                $.ajax({
                    url: '${pageContext.request.contextPath}/user/delete.do?id=' + obj.data['id'],
                    type: 'post',
                    success: function (result) {
                        layer.close(loading);
                        if (result.code == 200) {
                            layer.msg(result.msg, {
                                icon: 1,
                                time: 1000
                            }, function () {
                                obj.del();
                            });
                        } else {
                            layer.msg(result.msg, {
                                icon: 2,
                                time: 1000
                            });
                        }
                    }
                })
            });
        }

        window.assign = function (obj) {
            mainIndex = layer.open({
                type: 1,
                title: '分配角色',
                shade: 0.1,
                area: ['500px', '500px'],
                content: $('#user-form-assign').html(),
                success: function (layero, index) {
                    form.val('assignUserFrm', obj.data);
                    // 加载dtree的树形组件
                    dtree.render({
                        elem: "#roleTree",
                        url: "${pageContext.request.contextPath}/role/loadRolesTree.do?userId=" + obj.data.id,
                        checkbar: true,
                        checkbarType: "no-all",
                        dataStyle: "layuiStyle",  //使用layui风格的数据格式
                        dataFormat: "list",  //配置data的风格为list
                        response: {statusCode: 200},  //修改response中返回数据的定义
                        selectInputName: {
                            nodeId: "parentId"
                        }
                    });
                }
            });
        }

        window.batchRemove = function (obj) {

            var checkIds = common.checkField(obj, 'id');

            if (checkIds === "") {
                layer.msg("未选中数据", {
                    icon: 3,
                    time: 1000
                });
                return false;
            }
            layer.confirm('确定要删除这些用户', {
                icon: 3,
                title: '提示'
            }, function (index) {
                layer.close(index);
                let loading = layer.load();
                $.ajax({
                    url: '${pageContext.request.contextPath}/user/delete.do?id=' + checkIds,
                    type: 'post',
                    success: function (result) {
                        layer.close(loading);
                        if (result.code == 200) {
                            layer.msg(result.msg, {
                                icon: 1,
                                time: 1000
                            }, function () {
                                table.reload('user-table');
                            });
                        } else {
                            layer.msg(result.msg, {
                                icon: 2,
                                time: 1000
                            });
                        }
                    }
                })
            });
        }

        window.refresh = function (param) {
            table.reload('user-table');
        }

        form.on('submit(user-add)', function (obj) {
            console.log(obj);
            $.post("${pageContext.request.contextPath}/user/add.do", obj.field, function (result) {
                if (result.code == 200) {
                    // 新增成功
                    layer.msg(result.msg, {icon: 1, time: 1000}, function () {
                        layer.close(mainIndex);//关闭当前页
                        table.reload("user-table");
                    });
                    return;
                }
                layer.msg(result.msg, {icon: 2});
            })
            return false;
        })

        form.on('submit(user-update)', function (obj) {
            console.log(obj);
            $.post("${pageContext.request.contextPath}/user/update.do", obj.field, function (result) {
                if (result.code == 200) {
                    // 新增成功
                    layer.msg(result.msg, {icon: 1, time: 1000}, function () {
                        layer.close(mainIndex);//关闭当前页
                        table.reload("user-table");
                    });
                    return;
                }
                layer.msg(result.msg, {icon: 2});
            })
            return false;
        });

        form.on('submit(user-assign)', function (obj) {
            let params = dtree.getCheckbarNodesParam("roleTree");
            let roleIds = "";
            $.each(params, function (index, item) {
                roleIds += item.nodeId + ",";
            })
            roleIds = roleIds.substr(0, roleIds.length - 1);

            let data = {
                userId: obj.field.id,
                roleIds: roleIds
            };

            $.post("${pageContext.request.contextPath}/user/assign.do", data, function (result) {
                if (result.code == 200) {
                    // 新增成功
                    layer.msg(result.msg, {icon: 1, time: 1000}, function () {
                        layer.close(mainIndex);//关闭当前页
                        table.reload("user-table");
                    });
                    return;
                }
                layer.msg(result.msg, {icon: 2});
            })
            return false;
        });

        form.on('submit(close)', function () {
            table.reload("user-table");
            layer.close(mainIndex);
            return false;
        });
    })
</script>
</html>

